package com.ksvip.next.components.ons;

import java.util.Properties;

import org.springframework.beans.factory.InitializingBean;

import com.aliyun.openservices.ons.api.Consumer;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.PropertyKeyConst;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * 类AbstractOnsConsumer.java的实现描述：ONS监听基类,ons-client v1.8.4.Final
 * 版本资源隔离优化（实例化支持）
 *
 * @author 2021年8月13日 上午10:52:16
 */
@Getter
@Setter
@Slf4j
public abstract class AbstractOnsConsumer implements InitializingBean, MessageListener {

    /**
     * ONS topic
     */
    protected String topic;

    /**
     * ONS CID
     */
    protected String groupId;

    /**
     * TAG
     */
    protected String tag = "*";

    /**
     * AccessKey
     */
    protected String accessKey;

    /**
     * SecretKey
     */
    protected String secretKey;

    /**
     * ONS Addr
     */
    protected String namesrvAddr;

    /**
     * 创建bean时，启动监听
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("开始启动消息监听");
        final Properties properties = new Properties();
        properties.put(PropertyKeyConst.GROUP_ID, this.groupId);
        properties.put(PropertyKeyConst.AccessKey, this.accessKey);
        properties.put(PropertyKeyConst.SecretKey, this.secretKey);
        // 推荐配置。
        properties.put(PropertyKeyConst.NAMESRV_ADDR, this.namesrvAddr);
        // 兼容配置（不推荐继续使用，建议逐渐升级为推荐配置）。
        //  properties.put(PropertyKeyConst.ONSAddr, "xxxx");
        final Consumer consumer = ONSFactory.createConsumer(properties);
        this.doConsume(consumer);
    }

    /**
     * 模板方式消费消息
     *
     * @param consumer 消费者
     */
    private void doConsume(final Consumer consumer) {
        consumer.subscribe(this.topic, this.tag, this);
        consumer.start();
        log.info("消息监听启动成功{},gid={}", this.topic, this.groupId);
    }

}
